/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.Antecedent;
import it.polimi.games.epkb.entityClasses.AntecedentPK;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.GpiKpi;
import it.polimi.games.epkb.entityClasses.AssociationRule;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class AntecedentJpaController implements Serializable {

    public AntecedentJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }

        
    public AntecedentJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Antecedent antecedent) throws PreexistingEntityException, Exception {
        if (antecedent.getAntecedentPK() == null) {
            antecedent.setAntecedentPK(new AntecedentPK());
        }
        antecedent.getAntecedentPK().setIdGPIKPI(antecedent.getGpiKpi().getId());
        antecedent.getAntecedentPK().setIdRule(antecedent.getAssociationRule().getId());
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            GpiKpi gpiKpi = antecedent.getGpiKpi();
            if (gpiKpi != null) {
                gpiKpi = em.getReference(gpiKpi.getClass(), gpiKpi.getId());
                antecedent.setGpiKpi(gpiKpi);
            }
            AssociationRule associationRule = antecedent.getAssociationRule();
            if (associationRule != null) {
                associationRule = em.getReference(associationRule.getClass(), associationRule.getId());
                antecedent.setAssociationRule(associationRule);
            }
            em.persist(antecedent);
            if (gpiKpi != null) {
                gpiKpi.getAntecedentCollection().add(antecedent);
                gpiKpi = em.merge(gpiKpi);
            }
            if (associationRule != null) {
                associationRule.getAntecedentCollection().add(antecedent);
                associationRule = em.merge(associationRule);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findAntecedent(antecedent.getAntecedentPK()) != null) {
                throw new PreexistingEntityException("Antecedent " + antecedent + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Antecedent antecedent) throws NonexistentEntityException, Exception {
        antecedent.getAntecedentPK().setIdGPIKPI(antecedent.getGpiKpi().getId());
        antecedent.getAntecedentPK().setIdRule(antecedent.getAssociationRule().getId());
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Antecedent persistentAntecedent = em.find(Antecedent.class, antecedent.getAntecedentPK());
            GpiKpi gpiKpiOld = persistentAntecedent.getGpiKpi();
            GpiKpi gpiKpiNew = antecedent.getGpiKpi();
            AssociationRule associationRuleOld = persistentAntecedent.getAssociationRule();
            AssociationRule associationRuleNew = antecedent.getAssociationRule();
            if (gpiKpiNew != null) {
                gpiKpiNew = em.getReference(gpiKpiNew.getClass(), gpiKpiNew.getId());
                antecedent.setGpiKpi(gpiKpiNew);
            }
            if (associationRuleNew != null) {
                associationRuleNew = em.getReference(associationRuleNew.getClass(), associationRuleNew.getId());
                antecedent.setAssociationRule(associationRuleNew);
            }
            antecedent = em.merge(antecedent);
            if (gpiKpiOld != null && !gpiKpiOld.equals(gpiKpiNew)) {
                gpiKpiOld.getAntecedentCollection().remove(antecedent);
                gpiKpiOld = em.merge(gpiKpiOld);
            }
            if (gpiKpiNew != null && !gpiKpiNew.equals(gpiKpiOld)) {
                gpiKpiNew.getAntecedentCollection().add(antecedent);
                gpiKpiNew = em.merge(gpiKpiNew);
            }
            if (associationRuleOld != null && !associationRuleOld.equals(associationRuleNew)) {
                associationRuleOld.getAntecedentCollection().remove(antecedent);
                associationRuleOld = em.merge(associationRuleOld);
            }
            if (associationRuleNew != null && !associationRuleNew.equals(associationRuleOld)) {
                associationRuleNew.getAntecedentCollection().add(antecedent);
                associationRuleNew = em.merge(associationRuleNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                AntecedentPK id = antecedent.getAntecedentPK();
                if (findAntecedent(id) == null) {
                    throw new NonexistentEntityException("The antecedent with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(AntecedentPK id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Antecedent antecedent;
            try {
                antecedent = em.getReference(Antecedent.class, id);
                antecedent.getAntecedentPK();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The antecedent with id " + id + " no longer exists.", enfe);
            }
            GpiKpi gpiKpi = antecedent.getGpiKpi();
            if (gpiKpi != null) {
                gpiKpi.getAntecedentCollection().remove(antecedent);
                gpiKpi = em.merge(gpiKpi);
            }
            AssociationRule associationRule = antecedent.getAssociationRule();
            if (associationRule != null) {
                associationRule.getAntecedentCollection().remove(antecedent);
                associationRule = em.merge(associationRule);
            }
            em.remove(antecedent);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Antecedent> findAntecedentEntities() {
        return findAntecedentEntities(true, -1, -1);
    }

    public List<Antecedent> findAntecedentEntities(int maxResults, int firstResult) {
        return findAntecedentEntities(false, maxResults, firstResult);
    }

    private List<Antecedent> findAntecedentEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Antecedent.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Antecedent findAntecedent(AntecedentPK id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Antecedent.class, id);
        } finally {
            em.close();
        }
    }

    public int getAntecedentCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Antecedent> rt = cq.from(Antecedent.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
